package com.xw.controller.xw;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.xw.controller.base.BaseController;
import com.xw.entity.Page;
import com.xw.entity.system.User;
import com.xw.service.xw.caseOrder.CaseOrderService;
import com.xw.service.xw.image.ImageService;
import com.xw.service.xw.patient.PatientService;
import com.xw.util.AppUtil;
import com.xw.util.Const;
import com.xw.util.DateUtil;
import com.xw.util.FileUpload;
import com.xw.util.Jurisdiction;
import com.xw.util.PageData;
import com.xw.util.PathUtil;
/**
 * 类名称: CaseOrderController
 * 类描述: 病历单controller
 * @author : gce
 * @date   : 2017-12-1
 */
@Controller
@RequestMapping(value="/caseOrder")
public class CaseOrderController extends BaseController {
	
	String menuUrl = "caseOrder/list.do"; // 菜单地址(权限用)
	
	@Resource(name="caseOrderService")
	private CaseOrderService caseOrderService ;
	@Resource(name="patientService")
	private PatientService patientService ;
	@Resource(name="imageService")
	private ImageService imageService ;
	
	/**
	 * 新建病历前，条件查询列表（或姓名、或电话），若有指定患者#{hzId}，直接跳转到新建病历单页面
	 * @param page
	 * @throws Exception
	 * @return: ModelAndView
	 * @author: gce
	 * @date  : 2017-12-8
	 */
	@RequestMapping(value = "/findPatient")
	public ModelAndView findPatient(Page page) throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		if(pd.get("hzId")==null || pd.get("hzId").equals("") ){
			page.setPd(pd);
			List<PageData> allPatients = patientService.list(page);		//根据或姓名或电话查询 患者列表
			
			if(allPatients.size()==0){
				mv.addObject("has", 0);
				mv.setViewName("xw/caseOrder/choosePatient");
				//查询到一个，直接显示添加信息，
			}else if(allPatients.size()==1){
				mv.addObject("has", 1);
				int age = DateUtil.getAge((Date)allPatients.get(0).get("birth"));
				mv.addObject("patient", allPatients.get(0));
				mv.addObject("age", age);
				mv.setViewName("xw/caseOrder/addCaseOrder");
			}else{
				mv.addObject("has", 2);
				for (PageData pageData : allPatients) {
					int age = DateUtil.getAge((Date)pageData.get("birth"));
					pageData.put("age", age);
				}
				mv.addObject("allPatients", allPatients);
				mv.setViewName("xw/caseOrder/choosePatient");
			}
		}else{
			PageData pd2 = patientService.findById(pd);		//#{hzId}
			mv.addObject("has", 1);
			int age = DateUtil.getAge((Date)pd2.get("birth"));
			mv.addObject("patient", pd2);
			mv.addObject("age", age);
			mv.setViewName("xw/caseOrder/addCaseOrder");
		}
		mv.addObject("pd", pd);
		return mv ;
	}
	
	/**
	 * 查询病历单详情，根据病历单ID(#{id})
	 * @return: ModelAndView
	 * @author: gce
	 * @throws Exception 
	 * @date  : 2017-12-7
	 */
	@RequestMapping(value = "/findById")
	public ModelAndView findById() throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		pd = caseOrderService.findById(pd);							//#{id}
		int age = DateUtil.getAge((Date)pd.get("birth"));
		pd.put("age", age);
		//查询图片
		List<PageData> images = imageService.listByCaseId(pd);		//#{id}
		
		mv.addObject("caseOrder", pd);
		mv.addObject("images", images);
		mv.setViewName("xw/caseOrder/caseOrderDetail");
		return mv;
	}
	
	/**
	 * 查询病例列表 ，根据：或患者id  #{pd.hzId}
	 * @param page
	 * @throws Exception
	 * @return: ModelAndView
	 * @author: gce
	 * @date  : 2017-12-5
	 */
	@RequestMapping( value = "/list")
	public ModelAndView list(Page page) throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		page.setPd(pd);
		List<PageData> caseOrderList  = caseOrderService.list(page);
		mv.addObject("caseOrderList", caseOrderList);
		mv.addObject("pd", pd);
		mv.setViewName("xw/caseOrder/caseOrderList");
		return mv ;
	}
	
	
	/**
	 * 跳转到新建病历页面
	 * @return: ModelAndView
	 * @author: gce
	 * @date  : 2017-12-5
	 */
	@RequestMapping(value="/goAddCaseOrder")
	public ModelAndView goAddCaseOrder(){
		ModelAndView mv = this.getModelAndView();
		mv.setViewName("xw/caseOrder/choosePatient");
		return mv;
	}
	
	/**
	 * 添加病历单
	 * @return: Object
	 * @author: gce
	 * @throws Exception 
	 * @date  : 2017-11-30
	 */
	@RequestMapping(value="/saveCaseOrder")
	@ResponseBody
	public Object saveP(HttpServletRequest request,@RequestParam("file") CommonsMultipartFile[] files){
		Map<String, String> map = new HashMap<String, String>();
		String msg = "success";
		//病历单编号、患者ID、现病史、体温、体重、心率、收缩压、舒张压、诊断、医师ID、门诊ID、录入时间、修改时间、病历单状态  、  文件
		PageData pd = new PageData();
		try {
			pd.put("hzId",request.getParameter("hzId") );
			pd.put("xbs",request.getParameter("xbs") );
			pd.put("tw",request.getParameter("tw") );
			pd.put("tz",request.getParameter("tz") );
			pd.put("xl",request.getParameter("xl") );
			pd.put("ssy",request.getParameter("ssy") );
			pd.put("szy",request.getParameter("szy") );
			pd.put("zd",request.getParameter("zd") );
			
			Subject currentUser = SecurityUtils.getSubject();
			Session session = currentUser.getSession();
			User user = new User();
			user = (User)session.getAttribute(Const.SESSION_USER);
			
			pd.put("bldCode", " ");				//病历单编码
			pd.put("ysId", user.getUSER_ID());	//医师ID
			pd.put("mzId", user.getMzid());		//门诊id
			pd.put("createDate", new Date());	//录入时间
			pd.put("updateDate", new Date());	//修改时间
			pd.put("state", 0);					//状态	 0:正常，1：删除
			caseOrderService.save(pd);
			
			if(pd.get("id")!=null && pd.get("id")!=""){
				//判断并上传文件
				for (CommonsMultipartFile file : files) {
					String ffile = DateUtil.getDays();
					String fileName = "";
					if (null != file && !file.isEmpty()) {
						String filePath = PathUtil.getClasspath() + Const.FILEPATHIMG + ffile; 	// 文件上传路径
						fileName = FileUpload.fileUp(file, filePath, this.get32UUID()); 		// 执行上传,返回：UUID+后缀名
						PageData pd2 = new PageData();
						pd2.put("fileName",fileName );				//图片名称
						pd2.put("path", ffile + "/" + fileName);	//图片路径
						pd2.put("createTime",new Date() );			//录入时间
						pd2.put("suffix","" );						//文件后缀名
						pd2.put("blId",pd.get("id") );				//病历单ID
						imageService.save(pd2);
						
					}
				}
			}else{
				msg = "新增失败";
			}
			map.put("caseId", String.valueOf(pd.get("id")));
		} catch (Exception e) {
			msg = "新增失败";
			logger.error(e.toString(),e);
		}
		map.put("msg", msg);
		return AppUtil.returnObject(new PageData(), map);
	}
	
	//删除单个病历（caseOrderService.修改病历）（先判断病历单的医师id是否是当前医师id）
	/**
	 * 删除病历单: #{id}
	 * @param pd
	 * @throws Exception
	 * @return: int
	 * @author: gce
	 * @date  : 2017-12-7
	 */
	@RequestMapping(value = "/deleteOne")
	@ResponseBody
	public Object deleteOne(){
		Map<String, String> map = new HashMap<String, String>();
		String msg = "success";
		PageData pd = new PageData();
		try {
			pd = this.getPageData();
			//判断是否有删除权限
			if (Jurisdiction.buttonJurisdiction(menuUrl, "del")) {
				//有权限，再判断该病历单的医师 是否 是当前医师开的，是：可以删除；不是：不可以删
				Subject currentUser = SecurityUtils.getSubject();
				Session session = currentUser.getSession();
				User user = new User();
				user = (User)session.getAttribute(Const.SESSION_USER);
				pd = caseOrderService.findById(pd);
				if(pd.get("ysid").equals(user.getUSER_ID())){
					int result = caseOrderService.delete(pd);
					if(result>0){
					}else{
						msg = "删除失败";
					}
				}else{
					msg = "--不可删除，请联系该病历单医师--";
				}
			}else{
				logger.info("--没有删除权限--");
				msg = "--没有删除权限--";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
			msg = "--删除异常--";
		}
		map.put("msg", msg);
		return AppUtil.returnObject(new PageData(), map);
	}

}
